package cn.vic.util;

import java.io.*;

/**
 * 文件工具
 */
public class FileUtil {
    /**
     * 读取文件
     *
     * @param path
     * @return
     */
    public static String readFile(File path) {
        BufferedReader reader = null;
        StringBuffer contentBuffer = new StringBuffer();
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                contentBuffer.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return contentBuffer.toString();
    }

    /**
     * 输出文件
     *
     * @param path
     * @throws IOException
     */
    public static void write(String path, String content) {
        try {
            //将写入转化为流的形式
            BufferedWriter bw = new BufferedWriter(new FileWriter(path));
            //一次写一行
            bw.write(content);
            //换行用
            bw.newLine();
            //关闭流
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于保存
     * 如果没有盘符就表示为相对路径，
     * 有盘符且在本文件夹内，也是用相对路径
     *
     * @param path
     * @return
     */
    public static String getFilePathBySave(String path) {
        try {
            if (path == null) {
                return path;
            }
            //有盘符
            if (path.indexOf(":") > -1) {
                String directory = new File("").getCanonicalPath();
                return path.replace(directory, "");
            } else {
                return path;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    public static String getFilePathByRun(String path) {
        try {
            if (path == null) {
                return null;
            }
            //有盘符
            if (path.indexOf(":") > -1) {
                return path;
            } else {
                String directory = new File("").getCanonicalPath();
                return directory + File.separator + path;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

}
